package permission

import (
	"context"
	"fmt"
	"github.com/samber/lo"
	"private-domain-overseas-service/admin/business/api/internal/repository/permission"
	"private-domain-overseas-service/admin/business/api/internal/svc"
	"private-domain-overseas-service/admin/business/api/internal/types"
	"private-domain-overseas-service/pkg/xerr"
	"private-domain-overseas-service/tools/ent"
	"private-domain-overseas-service/tools/ent/adminuser"
	"private-domain-overseas-service/tools/ent/adminuserrole"
	"private-domain-overseas-service/tools/ent/predicate"
	"time"

	"github.com/zeromicro/go-zero/core/logx"
)

type AdminUserListLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

// NewAdminUserListLogic - 后台用户查询接口
func NewAdminUserListLogic(ctx context.Context, svcCtx *svc.ServiceContext) *AdminUserListLogic {
	return &AdminUserListLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *AdminUserListLogic) AdminUserList(req *types.AdminUserListRequest) (resp *types.AdminUserListResponse, err error) {
	adminUserDAO := permission.NewAdminUserDao(l.ctx, l.svcCtx)
	adminUserRoleDAO := permission.NewAdminUserRoleDao(l.ctx, l.svcCtx)

	// 分页查询用户信息
	conditions := make([]predicate.AdminUser, 0)
	if req.AdminUserUserName != "" {
		conditions = append(conditions, adminuser.AdminUserUsernameContains(req.AdminUserUserName))
	}
	if req.AdminUserStatus != 0 {
		conditions = append(conditions, adminuser.AdminUserStatusEQ(req.AdminUserStatus))
	}
	adminUsers, total, err := adminUserDAO.AdminUserConditionsPageAll(req, conditions)
	if err != nil {
		return nil, xerr.ErrCodeMsg(xerr.ServerOperationExceptionError, fmt.Sprintf("查询用户列表失败: %v", err.Error()))
	}

	// 根据用户ids查用户角色关联
	adminUserIds := lo.Map(adminUsers, func(item *ent.AdminUser, _ int) int64 {
		return int64(item.ID)
	})
	userRoleConditions := make([]predicate.AdminUserRole, 0, 1)
	userRoleConditions = append(userRoleConditions, adminuserrole.AdminUserRoleUserIDIn(adminUserIds...))
	adminUserRoles, err := adminUserRoleDAO.UserRoleConditionsAll(userRoleConditions)
	if err != nil {
		return nil, xerr.ErrCodeMsg(xerr.ServerOperationExceptionError, fmt.Sprintf("查询用户角色关联失败: %v", err.Error()))
	}

	// 构建用户id为key，角色id为value的map
	userRoleMap := make(map[int64][]int64)
	for _, item := range adminUserRoles {
		userRoleMap[item.AdminUserRoleUserID] = append(userRoleMap[item.AdminUserRoleUserID], item.AdminUserRoleRoleID)
	}

	// 组装数据，关联查到用户的角色id
	list := lo.Map(adminUsers, func(item *ent.AdminUser, _ int) *types.AdminUserInfo {
		return &types.AdminUserInfo{
			ID:                int64(item.ID),
			AdminUserUserName: item.AdminUserUsername,
			AdminUserPassword: item.AdminUserPassword,
			AdminUserNickName: item.AdminUserNickname,
			AdminUserEmail:    item.AdminUserEmail,
			AdminUserStatus:   item.AdminUserStatus,
			AdminUserRoleIds:  userRoleMap[int64(item.ID)],
			CreateAt:          item.CreateAt.Format(time.DateTime),
			UpdateAt:          item.UpdateAt.Format(time.DateTime),
		}
	})

	// 返回数据
	return &types.AdminUserListResponse{
		Page: &types.PageResponse{
			Total:           int64(total),
			PageSize:        int64(len(list)),
			RequestPageSize: req.PageSize,
			Current:         req.Current,
		},
		List: list,
	}, nil
}
